﻿/*
 * Created by SharpDevelop.
 * User: 1987wing
 * Date: 2016/7/19
 * Time: 23:16
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.IO;
using System.Collections.Generic;

namespace YMTSeller
{
	/// <summary>
	/// Description of FileUtils.
	/// </summary>
	public class FileUtils
	{
		public string path = "D:\\用户名.txt";
		
		public FileUtils()
		{
		}
		
		public void CreateFile()
        {
            var f = new FileStream(this.path, FileMode.OpenOrCreate);
            var sw = new StreamWriter(f);
            sw.Close();
            f.Close();
        }
		
		public string[] ReadFileByline()
        {
			string[] LineContent = {};
			
			if (!System.IO.File.Exists(this.path))
				this.CreateFile();
			else
        		LineContent = File.ReadAllLines(this.path);
			
            return LineContent;     
        }
		
		public void WriteFileByline(string content)
		{
			if (!System.IO.File.Exists(this.path))
				this.CreateFile();
			File.AppendAllText(this.path, content);
		}
		
		public bool isFileEmpty()
		{
			var fi = new FileInfo(this.path);
			
			if (fi.Length == 0)
				return true;
			else
				return false;
		}
		
		public void cleanFile()
		{
			FileStream fs = null;
			
			try{
				fs = new FileStream(this.path, FileMode.Truncate, FileAccess.ReadWrite);
			} catch(Exception e) {
				//e.Message;
			} finally {
				fs.Close();
			}
		}
		
		public void UpdateFile(string content)
		{
			string[] text = this.ReadFileByline();
			
			if (text == null)
				return;
			
			//if text.ToString()
			var dic = new Dictionary<string, string>();
			
			foreach (string t in text)
			{
				dic.Add(t.Split('/')[0], t.Split('/')[1]);
			}
			string te = content.Split('/')[0];
			
			if (!dic.ContainsKey(content.Split('/')[0]))
				dic.Add(content.Split('/')[0], content.Split('/')[1]);
			else
				dic[content.Split('/')[0]] = content.Split('/')[1];
			
			this.cleanFile();
			
			foreach (var item in dic)
            {
                this.WriteFileByline(item.Key + "/" + item.Value + "\n");
            }
		}
	}
}
